package CopyDirctory;

import java.io.*;

class CopyFiles {
    //copyFiles方法用于拷贝path目录到targetPath
    static void copyFiles(String path,String targetPath){
        int sum = 0;//拷贝成功的文件数量
        //创建文件夹
        File copyFile = new File(targetPath);
        if(!copyFile.exists()){
            copyFile.mkdirs();
        }
        //获取目录下的所有文件
        File[] files = new File(path).listFiles();
        for(File file:files){
            if(file.isDirectory()){
                copyFiles(file.getAbsolutePath(),targetPath+"\\"+file.getName());
            }
            if(file.isFile()){
                FileInputStream fis = null;
                FileOutputStream fos = null;
                try {
                    fis = new FileInputStream(file.getAbsoluteFile());

                    fos = new FileOutputStream(targetPath+"\\"+file.getName());
                    byte[] datas = new byte[1024*1024];
                    int len = 0;
                    while((len = fis.read(datas)) != -1){
                        fos.write(datas,0,len);
                    }
                    System.out.println("文件 "+file.getName()+" 拷贝成功");
                    sum++;
                    fos.flush();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
